<template>
  <common-page
    :title="this.title ? `编辑配置（${label}）` : `新增配置（${label}）`"
  >
    <div slot="header">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" @click="configureTest" :loading="buttonLoading"
        >测试</el-button
      >
      <el-button @click="submit" type="primary" :loading="isLoading"
        >保存</el-button
      >
    </div>

    <div slot="content" class="common-page-content-own">
      <el-form
        ref="form"
        :model="form"
        :inline="true"
        label-width="90px"
        :rules="rules"
        @submit.native.prevent
      >
        <common-group-title title="基本信息"></common-group-title>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关键字" prop="filterKey" class="configureItem">
              <common-input
                v-model="form.filterKey"
                placeholder="请输入关键字，以逗号分离"
                :disabled="this.title"
                :verify="false"
              >
              </common-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="表达式"
              prop="filterPattern"
              class="configureItem"
            >
              <span class="buttonAdd">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  plain
                  @click="handleAdd"
                  v-hasPermi="['analysiscenter:assetCategory:add']"
                  >添加
                </el-button>
              </span>
              <common-input
                type="textarea"
                ref="cursorPosition"
                v-model="form.filterPattern"
                :verify="false"
                :maxlength="4000"
                placeholder="请输入"
              >
              </common-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="测试日志"
              prop="filterExample"
              class="configureItem"
            >
              <common-input
                type="textarea"
                v-model="form.filterExample"
                :verify="false"
                :maxlength="4000"
                placeholder="请输入"
              >
              </common-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="测试结果"
              class="configureItem"
              v-if="this.testResult"
            >
              <common-input
                type="textarea"
                :verify="false"
                v-model="testResult"
                :maxlength="4000"
                placeholder="请输入"
              >
              </common-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="可用性" prop="sort" class="configureItem">
              <el-select v-model="form.sort" filterable clearable>
                <el-option
                  v-for="n in title ? content : content + 1"
                  :value="title ? content + 1 - n : content - n + 2"
                  :label="title ? content + 1 - n : content - n + 2"
                  :key="title ? content + 1 - n : content - n + 2"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" class="configureItem">
              <common-input
                type="textarea"
                v-model="form.remark"
                placeholder="请输入"
              >
              </common-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <common-edit-dialog
      :visible="open"
      @cancel="cancel"
      title="添加"
      @submit="submitData"
      width="800px"
    >
      <common-search @search="handleQuery" @reset="resetQuery">
        <el-form :model="queryParams" :inline="true" ref="queryForm">
          <el-form-item label="名称" prop="columnAlias">
            <common-input
              v-model="queryParams.columnAlias"
              @enter="handleQuery"
            >
            </common-input>
          </el-form-item>
        </el-form>
      </common-search>
      <common-table
        :data="List"
        isSetRowKey
        :row-key="'id'"
        @selection-change="handleSelectionChange"
        height="300px"
        v-loading="loading"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column label="名称" prop="columnAlias"></el-table-column>
        <el-table-column
          label="表达式"
          prop="columnParam"
          show-overflow-tooltip
        ></el-table-column>
      </common-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </common-edit-dialog>
  </common-page>
</template>

<script>
import {
  configureAdd,
  configureEdit,
  configureTest,
  expressionList,
  sortCount,
} from "@/api/analysisCenter/configure";
import CodeEditor from "@/components/CodeEditor";
import BaseList from "@/mixins/BaseList";
import HandleChooseDialog from "@/mixins/modules/HandleChooseDialog";

export default {
  mixins: [BaseList, HandleChooseDialog],
  name: "addconfigure",
  components: {
    CodeEditor,
  },
  props: {
    title: {
      type: Boolean,
      default: null,
    },
    configureId: {
      type: [Number, String],
      default: null,
    },
    configureData: {
      type: Object,
      default: () => ({}),
    },
    configAddId: {
      type: [Number, String],
      default: null,
    },
    addConfigureParentId: {
      type: String,
      default: "",
    },
    label: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      queryParams: {
        pageNum: 1, //页
        pageSize: 10, //一页中的数据条数
        columnAlias: "",
      },
      content: 0,
      total: 0,
      experssion: "",
      loading: false,
      open: false,
      List: [],
      buttonLoading: false,
      isLoading: false,
      testResult: "",
      form: {
        filterKey: null,
        filterExample: "",
        remark: null,
        filterPattern: "",
        sort: null,
        categoryParserruleId: null,
        assetCategoryId: null,
        isDefault: 0,
        parentId: this.addConfigureParentId,
      },
      rules: {
        filterKey: [
          { required: true, message: "请输入关键字", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请选择可用性", trigger: "blur" }],
        filterPattern: [
          { required: true, message: "请输入或选择表达式", trigger: "blur" },
        ],
      },
      start: 0,
      end: 0,
    };
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    //表达式
    handleAdd() {
      this.open = true;
      this.loading = true;
      this.queryParams.pageNum = 1;
      this.getList();
      let el = this.$refs.cursorPosition.$refs.input.$el.firstElementChild; //获取文本框
      if (el) {
        this.start = el.selectionStart;
        this.end = el.selectionEnd;
      }
    },
    //可用性
    getSortCount() {
      //编辑
      sortCount({ assetCategoryId: this.configAddId }).then((res) => {
        this.content = res.data;
      });
    },
    getList() {
      this.loading = true;
      const params = {
        indexId: "1406666658846097674",
        isSearch: 0,
        ...this.queryParams,
      };
      expressionList(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.List = res.rows;
            this.total = res.total;
          } else {
            this.List = [];
            this.total = 0;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    submitData() {
      if (typeof this.form.filterPattern === "string") {
        this.form.filterPattern =
          this.form.filterPattern.slice(0, this.start) +
          this.experssion +
          this.form.filterPattern.slice(this.start);
      } else {
        this.form.filterPattern = this.experssion;
      }
      this.open = false;
    },
    handleSelectionChange(selection) {
      this.experssion = selection.map((item) => item.columnParam).join("");
    },
    cancel() {
      this.open = false;
      this.queryParams.pageNum = 1;
    },
    configureTest() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          const params = {
            context: this.form.filterExample,
            pattern: this.form.filterPattern,
          };
          configureTest(params)
            .then((res) => {
              if (res && res.code === 200) {
                this.testResult = res.data || "";
                this.$GlobalSuccessMessage("操作成功");
              } else {
                this.testResult = "";
                this.$GlobalErrorConfirm("操作失败", res.msg);
              }
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },
    goBack() {
      this.$emit("closeView");
    },
    submit() {
      this.form.assetCategoryId = this.configAddId;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          
          if (this.title) {
            const params = {
              ...this.form,
              categoryParserruleId: this.configureId,
            };
            if (this.form.sort !== this.configureData.sort) {
              this.$confirm("可用性已使用，是否替换?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                this.isLoading = true;
                configureEdit(params)
                  .then((res) => {
                    if (res && res.code === 200) {
                      this.$emit("submit");
                      this.$GlobalSuccessMessage("编辑成功");
                    } else {
                      this.$GlobalErrorConfirm("编辑失败", res.msg);
                    }
                  })
                  .finally(() => {
                    this.isLoading = false;
                  });
              });
            } else {
              this.isLoading = true;
              configureEdit(params)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$emit("submit");
                    this.$GlobalSuccessMessage("编辑成功");
                  } else {
                    this.$GlobalErrorConfirm("编辑失败", res.msg);
                  }
                })
                .finally(() => {
                  this.isLoading = false;
                });
            }
          } else {
            this.isLoading = true;
            configureAdd(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$emit("submit");
                  this.$GlobalSuccessMessage("新增成功");
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.isLoading = false;
              });
          }
        }
      });
    },
    reset() {
      this.form.filterKey = "";
      this.form.filterExample = "";
      this.form.remark = "";
      this.form.filter_pattern = "";
      this.form.sort = "";
      this.form.categoryParserruleId = "";
    },
    data() {
      if (this.title) {
        this.form = { ...this.configureData };
      } else {
        this.reset();
      }
    },
  },
  mounted() {
    this.data();
    this.categoryParserruleId = this.configureId;
    this.getSortCount();
  },
};
</script>

<style scoped lang="scss">
::v-deep .common-page-content {
  overflow-y: auto !important;
}
.common-page-content-own {
  width: 50%;
  margin: 0 auto;
  padding-bottom: 12px;

  .buttonAdd {
    display: block;
    margin-bottom: 10px;
  }
}
::v-deep .common-search-wrap {
  margin-left: 20px !important;
}
.configureItem {
  width: 100%;

  ::v-deep .el-form-item__content {
    width: calc(100% - 90px) !important;
  }
}
</style>
